package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.Service.SetmealService;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Setmeal;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    //从属性文件中读取要生成的html对应的目录
    @Value("${out_put_path}")
    private String outPutPath;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        Integer setmealId = setmeal.getId();
        setSetmealAndCheckGroup(setmealId,checkgroupIds);
        //将保存到数据库的图片名称保存到redis集合中
        String img = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,img);

        //当添加套餐后需要重新生成静态页面（套餐列表页面、套餐详情页面）
        generateMobileStaticHtml();
    }

    //生成当前方法所需的静态页面
    private void generateMobileStaticHtml() {
        //在生成静态页面之前需要查询数据
        List<Setmeal> list = setmealDao.findAll();

        //需要生成套餐列表静态页面
        generateMobileSetmealListHtml(list);

        //需要生成套餐详情静态页面
        generateMobileSetmealDetailHtml(list);

    }

    //生成套餐列表静态页面
    private void generateMobileSetmealListHtml(List<Setmeal> list) {
        Map map = new HashMap();
        //为模板提供数据，用于生成静态页面
        map.put("setmealList",list);
        generteHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    //生成套餐详情静态页面（可能有多个）
    private void generateMobileSetmealDetailHtml(List<Setmeal> list) {
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal",setmealDao.findById(setmeal.getId()));
            generteHtml("mobile_setmeal_detail.ftl","setmeal_detail_" + setmeal.getId() + ".html",map);
        }
    }

    //通用的方法，用于生成静态页面
    //参数，模板名，生成的静态页面名，当前生成的页面
    public void generteHtml(String templateName,String htmlPageName,Map map){
        Configuration configuration = freeMarkerConfigurer.getConfiguration();//获取配置对象
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            out = new FileWriter(new File(outPutPath + "/" + htmlPageName));
            template.process(map,out);
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //获取当前页数
        Integer currentPage = queryPageBean.getCurrentPage();
        //获取显示个数
        Integer pageSize = queryPageBean.getPageSize();
        //查询条件
        String queryString = queryPageBean.getQueryString();
        //分页查询
        PageHelper.startPage(currentPage, pageSize);

        Page<CheckGroup> page = setmealDao.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    //查询所有
    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    //根据id查询
    @Override
    public Setmeal findById(int id) {
        return setmealDao.findById(id);
    }


    //根据套餐id查询检查组
    @Override
    public List<Integer> findCheckitemIdsByCheckgroupId(Integer id) {
        return setmealDao.findCheckitemIdsByCheckgroupId(id);
    }

    //编辑
    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //修改套餐基本信息
        setmealDao.edit(setmeal);
        //清理套餐当前管理检查组
        setmealDao.deleteAssocication(setmeal.getId());
        //重新建立套餐和检查组关联关系
        Integer setmealId = setmeal.getId();
        setSetmealAndCheckGroup(setmealId,checkgroupIds);
    }

    //删除套餐
    @Override
    public void delete(Integer id) {
        //根据套餐ID清理关联的检查组信息
        setmealDao.deleteAssocication(id);
        //删除当前套餐
        setmealDao.deleteById(id);

    }

    //套餐预约占比饼形图
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }

    //查询所有套餐名称
    public List<String> findSetmealNameCount() {
        return setmealDao.findSetmealNameCount();
    }

    //每个套餐的金额
    public Integer findSetmealMoney(Integer id) {
        return setmealDao.findSetmealMoney(id);
    }

    //查询每个套餐的id
    public Integer findnameById(String name) {
        return setmealDao.findnameById(name);
    }

    @Override
    public Double findSetmealNum(Integer id, ArrayList<String> dayList) {
        Double n = 0.0;
        for (String s : dayList) {
            //每天已到诊的预约套餐数量
            Integer num=setmealDao.findSetmealNum(id,s);
            n += num;
        }
        return n;
    }




    //提取修改和新增中重复代码，
    public void setSetmealAndCheckGroup(Integer setmealId, Integer[] checkgroupIds) {
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("setmealId", setmealId);
                map.put("checkgroupId", checkgroupId);
                setmealDao.setSetmealAndCheckGroup(map);
            }
        }
    }
}
